package com.lottotest;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements SensorEventListener {

	private long lastTime;
	private float speed;
	private float lastX;
	private float lastY;
	private float lastZ;
	private float x, y, z;

	// 민감도(수치가 낮을수록 민감)
	private static final int SHAKE_THRESHOLD = 1000;

	private static final int DATA_X = SensorManager.DATA_X;
	private static final int DATA_Y = SensorManager.DATA_Y;
	private static final int DATA_Z = SensorManager.DATA_Z;

	private SensorManager sensorManager;
	private Sensor accelerormeterSensor;

	Button button;
	TextView textview1;

	public int number[];
	public int temporaryNumber;
	public int changeNumber;

	static final int DIALOG_1 = 0;
	static final int EXIT_APP = 1;

	private static final String DEBUG_TAG = "{LOG_ANDROID}";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		makeNumber();

		sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		accelerormeterSensor = sensorManager
				.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

		button = (Button) findViewById(R.id.button1);

		textview1 = (TextView) findViewById(R.id.TextView01);

		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(MainActivity.this,
						ResultActivity.class);
				startActivity(intent);
			}
		});

	}

	@Override
	public void onStart() {
		super.onStart();
		if (accelerormeterSensor != null) {
			sensorManager.registerListener(this, accelerormeterSensor,
					SensorManager.SENSOR_DELAY_GAME);
		}
	}

	@Override
	public void onStop() {
		super.onStop();
		if (sensorManager != null) {
			sensorManager.unregisterListener(this);
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub

		if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
			long currentTime = System.currentTimeMillis();
			long gabOfTime = (currentTime - lastTime);

			// 센서 동작이 이전/이후 시간의 차이가 0.1초 이내이면
			if (gabOfTime > 100) {

				lastTime = currentTime;

				x = event.values[SensorManager.DATA_X];
				y = event.values[SensorManager.DATA_Y];
				z = event.values[SensorManager.DATA_Z];

				speed = Math.abs(x + y + z - lastX - lastY - lastZ) / gabOfTime
						* 7000;

				if (speed > SHAKE_THRESHOLD) {
					// 이벤트 발생!!

					numSuffle();

					textview1.setText(number[0] + ", " + number[1] + ", "
							+ number[2] + ", " + number[3] + ", " + number[4]
							+ ", " + number[5]);

					Vibrator vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
					vibe.vibrate(500);

					showDialog(DIALOG_1);

				}

				lastX = event.values[DATA_X];
				lastY = event.values[DATA_Y];
				lastZ = event.values[DATA_Z];
			}

		}

	}

	private void makeNumber() { // 1~45까지 번호 생성 함수

		number = new int[45];

		for (int i = 0; i < number.length; i++) {

			number[i] = i + 1;

		}

	}

	private void numSuffle() {

		for (int i = 0; i < 1000; i++) {
			changeNumber = (int) (Math.random() * 45);

			temporaryNumber = number[0];
			number[0] = number[changeNumber];
			number[changeNumber] = temporaryNumber;
		}

	}

	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_1:

			return new AlertDialog.Builder(MainActivity.this)
					.setTitle("안내")
					.setMessage("번호가 변경되었습니다.")
					.setPositiveButton("확인",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();

								}
							}).create();

		case EXIT_APP:

			return new AlertDialog.Builder(MainActivity.this)
					.setTitle("경고")
					.setMessage("종료하시겠습니까?")
					.setPositiveButton("확인",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									finish();
									System.exit(0);

								}
							})
					.setNegativeButton("취소",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();
								}
							}).create();

		}

		return null;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:

			showDialog(EXIT_APP);

		case KeyEvent.KEYCODE_HOME:
			ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
			am.restartPackage(getPackageName());
		}
		return super.onKeyDown(keyCode, event);
	}

}
